package vip.wangwenhao.autoconfigure.redis;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;

/**
 * @author wangwenhao
 */
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {

    /**
     * 使用Lettuce工厂初始化redis操作模板
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        return createRedisTemplate(redisConnectionFactory);
    }

    @Bean
    public RedisTemplate<String, Object> objectRedisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        return createRedisTemplate(redisConnectionFactory);
    }

    @Bean
    public RedisTemplate<String, String> customStringRedisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        return createRedisTemplate(redisConnectionFactory);
    }


    private<K,V> RedisTemplate<K,V> createRedisTemplate(LettuceConnectionFactory redisConnectionFactory){
        RedisTemplate<K, V> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        template.setDefaultSerializer(new FastJsonRedisSerializer<>(Object.class));
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        return template;
    }


    /**
     * 定义springSessionRedis的序列化方式
     *
     * @return
     */
//    @Bean
//    public FastJsonRedisSerializer springSessionDefaultRedisSerializer() {
//        return new FastJsonRedisSerializer(Object.class);
//    }
}